# -*- coding: utf-8 -*-
import cgi
import datetime
import time
import wsgiref.handlers
import random 

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp

import views.User as uv
import models.user as um

import models.role as rm

from models.enhancedModel import EnhancedModel

import decorator as dc

class UserContr( webapp.RequestHandler ):
    def debug_self(self, what, action, params, kwds):		# tylko do testów // nie jest wyświetlane
        self.response.out.write("<hr><font color=red face=bold>Informacje o zapytaniu:</font><br>")
        self.response.out.write("(%s)" % what)
        self.response.out.write("\n<br>" + action )
        for (i,p) in enumerate(params):
            self.response.out.write("\n<br>param %d = %s" % (i,p) )
        self.response.out.write("\n<br>kwds=%s" % str(kwds) )
        self.response.out.write("\n<br>url=%s" % ( self.request.url ) )
        self.response.out.write("\n<br>args=%s" % ( self.request.arguments() ) )
        for name in self.request.arguments():
            self.response.out.write("\n<br>arg: <b>%s</b>=%s" % ( name, self.request.get(name) ) )

        self.response.out.write( repr(type(uv)) )   ; self.response.out.write("\n<br>")
        self.response.out.write( repr(uv.__name__) ); self.response.out.write("\n<br>")
        self.response.out.write( repr(uv.__path__) ); self.response.out.write("\n<br>")
        self.response.out.write( repr(uv.__doc__) ) ; self.response.out.write("\n<br>")
        self.response.out.write( repr(uv.__file__) ); self.response.out.write("\n<br>")
        self.response.out.write( str((type(uv),dir(uv)))) ; self.response.out.write("\n<br>")
        self.response.out.write("<hr>")

    @dc.decorate
    def get(self, action, *params, **kwds):

        showArchival = self.request.get('archival') == 'True'
        
        permissionName = {"show1" : "usersShow",
                       "showAll" : "usersShow",
                       "edit" : "usersEdit",
                       "delete" : "usersDelete",
                       "new": "usersNew",
                       "populate": "admin"
                       }

        if not um.UserModel.currentHasPermission(permissionName[action]):
          self.response.out.write("<font color=\"red\"><b>You have no rights to do this action.</b></font>")
          return
        
        if action == 'show1': # pokaz1/id/numer # DONE
            if showArchival:
                q = EnhancedModel.queryAll( um.UserModel, int(params[0])) 
            else:
                q = EnhancedModel.queryLatest( um.UserModel, int(params[0])) 

            for (i,user) in enumerate(q):
                self.response.out.write("<h2>View user <i>"+str(user.account)+"</i></h2>")
                if um.UserModel.userRole() == 'admin' or um.UserModel.userRole() == 'shipper' :
                   self.response.out.write("<table><tr><td><b>Account</b></td><td><b>Role</b></td><td><b>Contact data</b></td><td><b>Archival</b></td><td><b>User's orders</b></td><td><b>Modify</b></td></tr>\n")
                elif um.UserModel.userRole() == 'manager' :
                   self.response.out.write("<table><tr><td><b>Account</b></td><td><b>Role</b></td><td><b>Contact data</b></td><td><b>Archival</b></td><td><b>User's orders</b></td></tr>\n")
                self.response.out.write(uv.show1(um.UserModel.userRole(), user ))
                self.response.out.write("\n</table>\n")

        elif action == 'showAll': # DONE
            if showArchival:
                q = EnhancedModel.queryAll( um.UserModel ) 
            else:
                q = EnhancedModel.queryLatest( um.UserModel )

            acc = self.request.get('account')
            if acc: 
               q.filter('account =', users.User(acc))    
            rol = self.request.get('role')
            if rol:
               q.filter('role =', rol)
            cdata = self.request.get('contactData')
            if cdata:
               q.filter('contactData =', cdata)
            self.response.out.write(uv.showAll(um.UserModel.userRole(), list(q) ))

        elif action == 'edit': # edit/id/numer #
            ident=int(params[0])
            self.response.out.write( uv.edit( um.UserModel.userRole(), EnhancedModel.queryLatest(um.UserModel, ident).get() ) )

        elif action == 'delete': # delete/id/numer
            user = EnhancedModel.queryLatest(um.UserModel, ident=int(params[0])).get()
            if user != None:
               self.response.out.write(uv.delete(um.UserModel.userRole(), user ))
            else:
               self.response.out.write("<font color=\"red\"><b>This user has been deleted before!</b></font>")
            
        elif action == 'new': # new # DONE
            showError = self.request.get( 'error' ) == 'True'
            if showError:
               self.response.out.write("<font color=\"red\"><b>Invalid user name!</b></font>")
            self.response.out.write(uv.new(um.UserModel.userRole()))
            
        elif action == 'populate': # funkcja testowa
            rs = ["admin", "shipper", "manager", "driver", "user", "pedestrian"]
            r = random.choice(rs)
            a = str(time.time())
            user = um.UserModel(role = r, account = users.User(a), contactData = "nn" )
            user.put()
            
            query = um.UserModel.all()
            
            for (i,result) in enumerate(query):
                self.response.out.write( cgi.escape( str((i,result, result.account, result.role, result.version, result.key()) ) ) + "<BR><BR>")

            
            

    def post(self, action, *params, **kwds):
        #self.debug_self('post', action, params, kwds)
        ident = -1
        # ^ what is it for? 
        
        permissionName = {"show1" : "usersShow",
                       "showAll" : "usersShow",
                       "edit" : "usersEdit",
                       "delete" : "usersDelete",
                       "new": "usersNew"
                       }
        
        if not um.UserModel.currentHasPermission(permissionName[action]):
          self.response.out.write("<font color=\"red\"><b>You have no rights to do this action.</b></font>")
          return

        if action == 'new':  # DONE
            acc = self.request.get('account')
            existing = um.UserModel.all().filter('account =', users.User(acc)).get()
            err = False

            if um.UserModel.userRole() == 'pedestrian' or um.UserModel.userRole() == 'user':
               rol = 'user'
            else:
               rol =  cgi.escape( self.request.get('role'))

            if existing != None:
               err = True
            if not err:
               user = um.UserModel( role = rol,
                                 account = users.User( cgi.escape(acc)),
                                 contactData = cgi.escape( self.request.get('contactData') ))
               user.put()
               ident = user.ident

               if um.UserModel.userRole() == 'pedestrian' or um.UserModel.userRole() == 'user':
                  self.redirect('/?done=True')
               else:
                  self.redirect('/user/show1/id/%d?done=True' % ident)
            else:
               self.redirect('/user/new?error=True')

        elif action == 'delete':
            old = EnhancedModel.queryLatest(um.UserModel, ident=int(params[0])).get()
            ident = old.ident
            if self.request.get('delete') == "NO":
              self.redirect('/user/show1/id/%d' % ident)
            else:
              old.deleteInstance()
              self.redirect('/user/show1/id/%d?archival=True&done=True' % ident)

        elif action == 'edit': # DONE
            if um.UserModel.userRole() == 'user':
               rol = 'user'
            else:
               rol =  cgi.escape( self.request.get('role'))

            old = EnhancedModel.queryLatest(um.UserModel, ident=int(params[0])).get()
            new = um.UserModel( role = rol,
                                account = old.account, # zmiany nazwy są problematyczne
                                contactData = cgi.escape( self.request.get('contactData')),
                                ident = old.ident
                                )
            EnhancedModel.deprecateOldVersion( new, old )

            ident = new.ident

            if um.UserModel.userRole() == 'user':
               self.redirect('/?done=True')
            else:
               self.redirect('/user/show1/id/%d?done=True' % ident)

        elif action == 'showAll': # DONE         
           opt = '?archival='+cgi.escape(self.request.get('archival'))
           rol = self.request.get('role')
           if rol != 'all':
              opt += '&role='+ cgi.escape(rol)
           acc = self.request.get('account')
           if acc:
              opt += '&account='+ cgi.escape(acc)
           cdata = self.request.get('contactData')
           if cdata:
              opt += '&contactData='+ cgi.escape(cdata)

           self.redirect('/user/showAll'+opt)
